/*
 * IC Project - a prototype to test a hypothesis of collective intelligence
 * Copyright (C) 2012 Paolo Conte - paolo@concavi.net
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Affero General Public License for more details.
 * 
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * This code is derived from the project ojoverse (2008, same author)
 * under the license GPL2. See <http://www.gnu.org/licenses/>.
 */

package org.ix.utils;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.ix.data.manager.P2PBroker;

public class Serialize {

    public static boolean writeToFile(Serializable obj, String fileName) {
        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(obj);
            oos.close();
            return true;
        } catch (FileNotFoundException fnfexc) {
            Logger.getLogger(P2PBroker.class.getName()).log(Level.SEVERE, null, fnfexc);
        } catch (IOException ioexc) {
            Logger.getLogger(P2PBroker.class.getName()).log(Level.SEVERE, null, ioexc);
        }
        return false;
    }

    public static Serializable readFromFile(String fileName) {
        try {
            FileInputStream fin = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(fin);
            Serializable obj = (Serializable) ois.readObject();
            ois.close();
            return obj;
        } catch (FileNotFoundException fnfexc) {
            Logger.getLogger(P2PBroker.class.getName()).log(Level.INFO, null, fnfexc);
        } catch (IOException ioexc) {
            Logger.getLogger(P2PBroker.class.getName()).log(Level.WARNING, null, ioexc);
        } catch (ClassNotFoundException cnfexc) {
            Logger.getLogger(Serialize.class.getName()).log(Level.WARNING, null, cnfexc);
        }
        return null;
    }
}
